import 'package:flutter/cupertino.dart';
import 'package:flutter/rendering.dart';

class CustomCenter extends SingleChildRenderObjectWidget {
  const CustomCenter({super.key, required Widget child}) : super(child: child);

  @override
  RenderObject createRenderObject(BuildContext context) {
    return RenderCustomCenter();
  }
}
class RenderCustomCenter extends RenderShiftedBox {
  RenderCustomCenter() : super(null);

  // 重写自定义布局逻辑的方法
  @override
  void performLayout() {
    // 判断子组件是否为空
    if (child != null) {
      // 若存在子组件，继续向下传递布局约束
      child!.layout(
        BoxConstraints(
          minWidth: 0.0,
          maxWidth: constraints.maxWidth,
          minHeight: 0.0,
          maxHeight: constraints.maxHeight,
        ),
        parentUsesSize: true, // 布局组件需要根据子组件的大小做相关调整
      );

      // 根据布局约束定义布局组件CustomCenter的大小
      size = Size(
          constraints.maxWidth,
          constraints.maxHeight);
      // 若存在子组件，则布局子组件
      centerChild();
    } else {
      size = Size(
          constraints.maxWidth,
          constraints.maxHeight);
    }
  }
  void centerChild() {
    final double centerX = (size.width - child!.size.width) / 2.0;
    final double centerY = (size.height - child!.size.height) / 2.0;

    // 指定子组件的偏移量
    final BoxParentData childParentData = child!.parentData as BoxParentData;
    childParentData.offset = Offset(centerX, centerY);
  }
}
